public class Test02 {
    public String longestPalindrome(String s) {
        int begin = 0, length = 0, n = s.length();

        for(int i = 0; i < n; i++){
            // 奇数长度回文
            int left = i, right = i;
            while (left >= 0 && right < n && s.charAt(left) == s.charAt(right)) {
                left--; right++;
            }
            if (right - left - 1 > length) {
                begin = left + 1;
                length = right - left - 1;
            }

            // 偶数长度回文
            left = i; right = i + 1;
            while (left >= 0 && right < n && s.charAt(left) == s.charAt(right)) {
                left--; right++;
            }
            if (right - left - 1 > length) {
                begin = left + 1;
                length = right - left - 1;
            }
        }
        return s.substring(begin, begin + length);
    }
}
